package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.dao.NorthSeaTideMapper;
import com.xxl.job.executor.model.NorthSeaTide;
import com.xxl.job.executor.utils.CmUtil;
import com.xxl.job.executor.utils.ConstUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;

/*
"海洋（潮高）数据抓取";
 */

@Component
public class SeaTideTask {
    private static Logger logger = LoggerFactory.getLogger(SeaTideTask.class);


    private String taskContents;
    @Autowired
    private ConstUtil constUtil;
    @Autowired
    private NorthSeaTideMapper northSeaTideMapper;

    @XxlJob(value = "SeaTideTask",init = "init", destroy = "destroy")
    public ReturnT<String> SeaTideTask(String param) throws Exception {
//        if (constUtil == null) {
//            constUtil = SpringContextHolder.getBean(ConstUtil.class);
//        }
//        if (northSeaTideMapper == null) {
//            northSeaTideMapper = SpringContextHolder.getBean(NorthSeaTideMapper.class);
//        }
        // 获取文本内容
        Document doc = getHtml(constUtil);
        if(doc == null) {
            System.out.println("null");
        };
        // 获取24小时内潮高数据
        Elements elements = doc.select("[class=tideCon]").first().select("td");
        ArrayList<String> tideList= new ArrayList<>();
        // 第一高潮时
        String firstHighTime = elements.get(0).text();
        tideList.add(firstHighTime);
        // 第一高潮位(cm)
        String firstHigh = elements.get(1).text();
        tideList.add(firstHigh);
        // 第一低潮时
        String firstLowTime = elements.get(2).text();
        tideList.add(firstLowTime);
        // 第一低潮位(cm)
        String firstLow = elements.get(3).text();
        tideList.add(firstLow);
        // 第二高潮时
        String secondHighTime = elements.get(4).text();
        tideList.add(secondHighTime);
        // 第二高潮位(cm)
        String secondHigh = elements.get(5).text();
        tideList.add(secondHigh);
        // 第二低潮时
        String secondLowTime = elements.get(6).text();
        tideList.add(secondLowTime);
        // 第二低潮位(cm)
        String secondLow = elements.get(7).text();
        tideList.add(secondLow);
        // 获取发布时间
        String publishDate = doc.select("[class=tideTimeone]").select("span").attr("data").trim();
        // 获取预报日期
        String forecastDate = doc.select("[class=tideTimeone]").select("span").attr("data").trim();
        NorthSeaTide northSeaTide;
        // 根据预报日期查询是否有当天的潮高数据
        northSeaTide = northSeaTideMapper.selectByForecastDate(forecastDate);
        if(northSeaTide==null){
            // 不存在，插入一条数据
            try{
                northSeaTide = new NorthSeaTide();
                northSeaTide.setSeaTideId(CmUtil.getUUID());
                //预报日期
                northSeaTide.setForecastDate(forecastDate);
                // 发布时间
                northSeaTide.setPublishDate(publishDate);
                //northSeaTide.setSyncTime(publishDate);
                northSeaTide.setSeaName("青岛沿岸");
                // 第一高潮时
                northSeaTide.setFirstHighTime(firstHighTime);
                // 第一高潮位
                northSeaTide.setFirstHigh(firstHigh);
                // 第一低潮时
                northSeaTide.setFirstLowTime(firstLowTime);
                // 第一低潮位
                northSeaTide.setFirstLow(firstLow);
                // 第二高潮时
                northSeaTide.setSecondHighTime(secondHighTime);
                // 第二高潮位
                northSeaTide.setSecondHigh(secondHigh);
                // 第二低潮时
                northSeaTide.setSecondLowTime(secondLowTime);
                // 第二低潮位
                northSeaTide.setSecondLow(secondLow);
                northSeaTideMapper.insertSelective(northSeaTide);
                this.taskContents = "插入青岛沿岸"+"  "+forecastDate+"   潮高数据成功！";
            }catch (Exception e){
                e.printStackTrace();
                this.taskContents = "插入青岛沿岸"+"  "+forecastDate+"   潮高数据异常！";
            }
        }
        else if(!northSeaTide.toString().equals(tideList.toString())){
            try{
                // 更新已有数据
                // 发布时间
                northSeaTide.setPublishDate(publishDate);
                // 第一高潮时
                northSeaTide.setFirstHighTime(firstHighTime);
                // 第一高潮位
                northSeaTide.setFirstHigh(firstHigh);
                // 第一低潮时
                northSeaTide.setFirstLowTime(firstLowTime);
                // 第一低潮位
                northSeaTide.setFirstLow(firstLow);
                // 第二高潮时
                northSeaTide.setSecondHighTime(secondHighTime);
                // 第二高潮位
                northSeaTide.setSecondHigh(secondHigh);
                // 第二低潮时
                northSeaTide.setSecondLowTime(secondLowTime);
                // 第二低潮位
                northSeaTide.setSecondLow(secondLow);
                northSeaTideMapper.updateByPrimaryKeySelective(northSeaTide);
                this.taskContents = "更新青岛沿岸"+"  "+forecastDate+"   潮高数据成功！";
            }catch (Exception e){
                e.printStackTrace();
                this.taskContents = "更新青岛沿岸"+"  "+forecastDate+"   潮高数据异常！";
            }
        }

        return ReturnT.SUCCESS;
    }
    /**
     * 获取HTML内容
     *
     * @param constUtil
     * @return
     */
    public static Document getHtml(ConstUtil constUtil) {
        Document doc = null;
        try {
            if (constUtil.useProxy) {
                // 设置代理
                Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(constUtil.proxyId, constUtil.proxyPort));
                doc = Jsoup.connect(constUtil.seaTideUrl)
                        .proxy(proxy)
                        .userAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
                        .timeout(999999999)
                        .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                        .header("Accept-Encoding", "gzip, deflate")
                        .header("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
                        .header("Connection", "keep-alive")
                        //是忽略请求类型
                        .ignoreContentType(true)
                        .get();
            } else {
                doc = Jsoup.connect(constUtil.seaTideUrl)
                        .userAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
                        .timeout(999999999)
                        .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                        .header("Accept-Encoding", "gzip, deflate")
                        .header("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
                        .header("Connection", "keep-alive")
                        //是忽略请求类型
                        .ignoreContentType(true)
                        .get();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }

    public void init(){
        logger.info("init");
    }
    public void destroy(){
        logger.info("destory");
    }
}
